package thread;

public class DeadLock
{
    public static void main(String[] args)
    {
        DeadLockThread d = new DeadLockThread();
        new Thread(d).start();
        d.init();
    }

    static class A
    {
        public synchronized void foo(B b)
        {
            System.out.println(Thread.currentThread().getName() + "进入A类的foo()方法");
            try
            {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + "企图调用b对象的last()方法");
                b.last();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        public synchronized void last()
        {
            System.out.println(Thread.currentThread().getName() + "调用A类的last()方法");
        }
    }

    static class B
    {
        public synchronized void foo(A a)
        {
            System.out.println(Thread.currentThread().getName() + "进入B类的foo()方法");
            try
            {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + "企图调用a对象的last()方法");
                a.last();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        public synchronized void last()
        {
            System.out.println(Thread.currentThread().getName() + "调用B类的last()方法");
        }
    }

    static class DeadLockThread implements Runnable
    {
        A a = new A();
        B b = new B();

        public void init()
        {
            Thread.currentThread().setName("主线程");
            a.foo(b);
        }

        @Override
        public void run()
        {
            Thread.currentThread().setName("子线程");
            b.foo(a);
        }
    }
}